<template>
    <div class="reset-wrapper" :class="{ 'dark-mode': isDark }">
        <!-- 步骤条 -->
        <div class="steps-container">
            <el-steps :active="active" finish-status="success" align-center>
                <el-step title="验证电子邮件"/>
                <el-step title="重新设定密码"/>
            </el-steps>
        </div>

        <!-- 标题 -->
        <div class="header">
            <h2>重置密码</h2>
            <p v-if="active === 0">请输入需要重置密码的电子邮件地址</p>
            <p v-else>请填写您的新密码，务必牢记，谨防丢失</p>
        </div>

        <!-- 表单 + 按钮区域 -->
        <div class="form-and-btn">
            <el-form :model="form" :rules="rule" ref="formRef" class="form">
                <!-- 步骤 1 -->
                <template v-if="active === 0">
                    <el-form-item prop="email">
                        <el-input
                                v-model="form.email"
                                type="email"
                                placeholder="电子邮件地址"
                                clearable
                                :prefix-icon="Message"
                        />
                    </el-form-item>

                    <el-form-item prop="code">
                        <div class="code-row">
                            <el-input
                                    v-model="form.code"
                                    maxlength="6"
                                    placeholder="请输入验证码"
                                    clearable
                                    :prefix-icon="Edit"
                            />
                            <el-button
                                    type="success"
                                    :disabled="!isEmailValid || coldTime"
                                    @click="askCode"
                            >
                                {{ coldTime > 0 ? `请稍后${coldTime}秒` : '获取验证码' }}
                            </el-button>
                        </div>
                    </el-form-item>
                </template>

                <!-- 步骤 2 -->
                <template v-else>
                    <el-form-item prop="password">
                        <el-input
                                v-model="form.password"
                                maxlength="20"
                                type="password"
                                placeholder="新密码"
                                clearable
                                show-password
                                :prefix-icon="Lock"
                        />
                    </el-form-item>

                    <el-form-item prop="password_repeat">
                        <el-input
                                v-model="form.password_repeat"
                                maxlength="20"
                                type="password"
                                placeholder="重复密码"
                                clearable
                                show-password
                                :prefix-icon="Lock"
                        />
                    </el-form-item>
                </template>
            </el-form>

            <el-button
                    v-if="active === 0"
                    class="register-btn"
                    type="warning"
                    plain
                    @click="confirmReset()"
            >
                开始重置
            </el-button>
            <el-button
                    v-else
                    class="register-btn"
                    type="danger"
                    plain
                    @click="doReset()"
            >
                立即重置
            </el-button>
        </div>

        <!-- 底部登录链接 -->
        <div class="login-link">
            <span>记得密码了？</span>
            <el-link @click="goLogin()" class="login-link-text">立即登录</el-link>
        </div>
    </div>
</template>

<script setup>
import {reactive, ref, computed} from 'vue'
import {Message, Edit, Lock} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {get, post} from '@/net/index.js'
import router from '@/router/index.js'
import {useDark} from '@vueuse/core'

const isDark = useDark()
const active = ref(0)
const coldTime = ref(0)
const timer = ref(null)
const formRef = ref()

const form = reactive({
    email: '',
    code: '',
    password: '',
    password_repeat: ''
})

const validatePassword = (rule, value, callback) => {
    if (!value) callback(new Error('请再次输入密码'))
    else if (value !== form.password) callback(new Error('两次输入的密码不一致'))
    else callback()
}

const rule = {
    email: [
        {required: true, message: '请输入邮件地址', trigger: 'blur'},
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ],
    code: [{required: true, message: '请输入验证码', trigger: 'blur'}],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, max: 20, message: '密码应为6-20位', trigger: ['blur', 'change']}
    ],
    password_repeat: [{validator: validatePassword, trigger: ['blur', 'change']}]
}

const isEmailValid = computed(() => /^[\w.-]+@[\w.-]+\.\w+$/.test(form.email))

function askCode() {
    if (!isEmailValid.value) return ElMessage.warning('请输入正确的电子邮件')
    coldTime.value = 60
    if (timer.value) clearInterval(timer.value)

    get(`/api/auth/ask-code?email=${form.email}&type=reset`, () => {
        ElMessage.success(`验证码已发送到邮箱: ${form.email}`)
        timer.value = setInterval(() => {
            coldTime.value--
            if (coldTime.value <= 0) {
                clearInterval(timer.value)
                timer.value = null
            }
        }, 1000)
    }, (msg) => {
        ElMessage.warning(msg)
        coldTime.value = 0
    })
}

function confirmReset() {
    formRef.value.validate(valid => {
        if (valid) {
            post('api/auth/reset-confirm', {email: form.email, code: form.code}, () => {
                active.value = 1
            })
        }
    })
}

function doReset() {
    formRef.value.validate(valid => {
        if (valid) {
            post('/api/auth/reset-password', {
                password: form.password,
                password_repeat: form.password_repeat,
                email: form.email,
                code: form.code
            }, () => {
                ElMessage.success('密码重置成功，请重新登录')
                router.push('/')
            })
        }
    })
}

function goLogin() {
    router.push('/')
}
</script>

<style scoped>
.reset-wrapper {
    max-width: 340px;
    margin: 0 auto;
    padding: 1.25rem 1rem;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100%;
    user-select: none;
    transition: background-color 0.3s, color 0.3s;
}

/* 步骤条 */
.steps-container {
    flex-shrink: 0;
    padding: 1.5rem 0 1rem;
}

/* 标题 */
.header {
    text-align: center;
    margin-bottom: 1.5rem;
}

.header h2 {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.header p {
    font-size: 0.875rem;
    color: var(--el-text-color-secondary);
}

/* 表单 */
.form {
    display: flex;
    flex-direction: column;
    gap: 0.375rem;
    margin-bottom: 0;
    padding-bottom: 0;
}

::v-deep(.el-input__wrapper) {
    border-radius: 0.625rem;
    height: 2.625rem;
    font-size: 0.875rem;
}

::v-deep(.el-form-item) {
    margin-bottom: 0.7rem;
}

/* 验证码输入 */
.code-row {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    width: 100%;
}

::v-deep(.code-row .el-button) {
    width: 8.125rem;
    flex-shrink: 0;
    height: 2.625rem;
    border-radius: 0.625rem;
}

/* 按钮 */
.register-btn {
    margin-top: 1.5rem;
    width: 100%;
    height: 2.625rem;
    border-radius: 0.625rem;
    font-size: 1rem;
}

/* 登录链接 */
.login-link {
    margin-top: 1rem;
    text-align: center;
}

.login-link span {
    font-size: 0.875rem;
    color: var(--el-text-color-secondary);
}

.login-link-text {
    margin-left: 0.25rem;
    color: var(--el-color-primary);
    cursor: pointer;
    transition: color 0.3s;
}

/* 深色模式 */
.dark-mode {
    background-color: #181818;
    color: #e5e5e5;
}

.dark-mode .header p,
.dark-mode .login-link span {
    color: #aaa;
}

.dark-mode ::v-deep(.el-input__wrapper) {
    background-color: #2a2a2a;
    border-color: #444;
    box-shadow: inset 0 0 0 1px #444;
}

.dark-mode ::v-deep(.el-input__inner) {
    color: #f0f0f0;
}

.dark-mode .login-link-text {
    color: #66b1ff;
}

.dark-mode .login-link-text:hover {
    color: #409eff;
}
</style>